package cc.rboot.lock.core;

import org.redisson.api.RLock;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Locker implements Closeable, java.util.concurrent.locks.Lock {

    private java.util.concurrent.locks.Lock lock;

    public Locker(RLock lock) {
        this.lock = lock;
    }

    public Locker(ReentrantLock lock) {
        this.lock = lock;
    }

    @Override
    public void close() throws IOException {
        this.unlock();
    }

    public void lock() {
        this.lock.lock();
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        lock.lockInterruptibly();
    }

    @Override
    public boolean tryLock() {
        return lock.tryLock();
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return lock.tryLock(time, unit);
    }

    public void unlock() {
        if(lock instanceof RLock) {
            if(((RLock)lock).isHeldByCurrentThread()) {
                lock.unlock();
            }
        } else {
            lock.unlock();
        }
    }

    @Override
    public Condition newCondition() {
        return lock.newCondition();
    }
}
